package com.jplus.core.mvc.reqeust.defaults;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Map;

import com.jplus.core.core.ApplicationContext;
import com.jplus.core.mvc.WebContext;
import com.jplus.core.mvc.WebUtil;
import com.jplus.core.mvc.anno.PathVariable;
import com.jplus.core.mvc.anno.ReqeustBody;
import com.jplus.core.mvc.anno.RequestParam;
import com.jplus.core.mvc.reqeust.ContentTypeEnum;
import com.jplus.core.mvc.reqeust.RequestHandle;
import com.jplus.core.utill.ConvertUtil;
import com.jplus.core.utill.JSON;

public class FormReqeustHandle extends RequestHandle {
	private ConvertUtil CU = ConvertUtil.newInstance();

	public FormReqeustHandle() {
		super.register(ContentTypeEnum.APPFORM.type, this);
	}

	/**
	 * 组装请求入参
	 * 
	 * 支持：
	 * 
	 * @PathVariable URL入参、
	 * @RequestParam 键值入参
	 * @RequestBody 表单对象入参
	 */
	@Override
	public Object[] buildRequstParam(Method method, ApplicationContext context) {
		Object[] params = new Object[method.getParameterCount()];
		try {
			Map<String, Object> reqParams = WebUtil.getRequestParamMap();
			Map<String, String> reqRestful = WebContext.getRestfulParam();

			Class<?>[] paramCla = method.getParameterTypes();
			Annotation[][] paramAns = method.getParameterAnnotations();

			for (int i = 0; i < params.length; i++) {
				Class<?> cla = paramCla[i];
				Object val = null;
				Annotation[] an = paramAns[i];
				for (Annotation a : an) {
					// ==1,按注解赋值
					if (a instanceof PathVariable) {
						PathVariable pv = (PathVariable) a;
						val = CU.convert((reqRestful.get(pv.value())), cla);
					} else if (a instanceof RequestParam) {
						RequestParam rm = (RequestParam) a;
						Object obj = reqParams.get(rm.value());
						if (rm.required() == true && obj == null)
							throw new NullPointerException("The argument cannot be empty：" + rm.value());
						if (rm.required() == false && obj == null)
							obj = rm.defaultValue();
						val = CU.convert(obj, cla);
					} else if (a instanceof ReqeustBody) {
						val = JSON.parseBean(JSON.toJSONString(reqParams), cla);
					}
				}
				// ==2,按类型赋值【默认4钟http对象类型】
				if (val == null)
					val = getHttpServlet(cla);
				// == 类型格式化 =======================
				params[i] = val;
			}

		} catch (Exception e) {
			throw new RuntimeException("Action param convert ERROR:" + method.toGenericString(), e);
		}
		return params;
	}

}
